﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ReadWaterlevelData
{
    public partial class OptionForm : Form
    {
        WaterlevelSettings settings;
        System.Configuration.Configuration config;

        public OptionForm(WaterlevelSettings s, System.Configuration.Configuration config)
        {
            InitializeComponent();
            this.config = config;

            settings = s;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            config.Sections.Remove("mySettings");
            if (settings == null)
            {
                settings = new WaterlevelSettings();
            }

            settings.BaseDate = DateTime.Parse(txtDate.Value.ToString("yyyy-MM-dd") + " " + txtTime.Text);
            settings.Interval = Int32.Parse((txtHour.Value * 60 + txtMinute.Value).ToString());
            settings.AutoRead = chkAuto.Checked;

            //ConfigurationManager.RefreshSection("mySettings");
            //ConfigurationSection section = config.Sections["mySettings"];
            //section  == null && !section.ElementInformation.IsLocked
            if (config.Sections["mySettings"] == null)
            {
                config.Sections.Add("mySettings", settings);
            }

            config.Save();
            System.Configuration.ConfigurationManager.RefreshSection("mySettings");

            MainForm mainForm = this.Owner as MainForm;
            mainForm.settings = this.settings;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void OptionForm_Load(object sender, EventArgs e)
        {
            //WaterlevelSettings oldSettings = SettingsManager.GetSettings();

            if (settings == null || settings.BaseDate == DateTime.MinValue)
            {
                txtDate.Value = DateTime.Now.Date;// DateTime.Parse(settings.BaseDate);
                txtTime.Value = DateTime.Now.Date.AddHours(8).AddMinutes(2);//DateTime.Parse(settings.BaseDate);
                txtHour.Value = 12;
                txtMinute.Value = 0;

                MessageBox.Show("您这是初次设置运行参数，请保存设置后，关闭程序，并再次打开！", "警告");
            }
            else
            {
                //if (settings.BaseDate < DateTime.Now.Date)
                //{
                //    settings.BaseDate = DateTime.Now.Date;
                //}
                //settings.BaseDate = DateTime.Now.Date;
                txtDate.Value = settings.BaseDate;// DateTime.Parse(settings.BaseDate);
                txtTime.Value = settings.BaseDate;//DateTime.Parse(settings.BaseDate);
                txtHour.Value = settings.Interval / 60;
                txtMinute.Value = settings.Interval % 60;
            }
        }
    }
}
